using Share.Audio;
using System;
using UnityEngine;

namespace Share
{
    /// <summary>
    /// 音频管理器，负责管理游戏中的各种音效
    /// </summary>
    public sealed class AudioManager : SingletonMonoObject<AudioManager>
    {
        float m_fBgmVolume = 1.0f;
        float m_fEffectVolume = 1.0f;

        private AudioBGM m_BgmPlayer = null;
        private AudioOneShot m_OneShotPlayer = null;
        private AudioGroup m_SkillPlayer = null;
        private AudioGroup m_ScenePlayer = null;
        private AudioGroup m_UIPlayer = null;

        public void SetMusicVolume(float value)
        {
            m_fBgmVolume = value;
            m_BgmPlayer?.SetVolume(value);

        }

        public void SetMusicSpeed(float fSpeed)
        {
            m_BgmPlayer?.SetSpeed(fSpeed);
        }
        public void SetEffectVolume(float value)
        {
            m_fEffectVolume = value;
            m_OneShotPlayer?.SetVolume(value);
            m_SkillPlayer?.SetVolume(value);
            m_ScenePlayer?.SetVolume(value);
            m_UIPlayer?.SetVolume(value);
        }


        private object lockObject = new object();
        /// <summary>
        /// 获取AudioManager单例实例
        /// </summary>

        private AudioManager()
        {
            // 注册应用暂停/恢复事件
        }

        ~AudioManager()
        {
        }

        /// <summary>
        /// 初始化音频播放器
        /// </summary>
        /// <param name="player">音频播放器实例</param>
        /// <param name="name">游戏对象名称</param>
        /// <returns>初始化后的音频播放器</returns>
        private T InitializePlayer<T>(ref T player, string name) where T : Component
        {
            if (player == null)
            {
                lock (lockObject)
                {
                    if (player == null)
                    {
                        try
                        {
                            var obj = new GameObject(name);
                            obj.transform.parent = transform;
                            DontDestroyOnLoad(obj);
                            player = obj.AddComponent<T>();
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError($"Failed to initialize {name}: {ex.Message}");
                        }
                    }
                }
            }
            return player;
        }

        /// <summary>
        /// 播放背景音乐（带开场和循环部分）
        /// </summary>
        /// <param name="startName">开场音乐名称</param>
        /// <param name="loopName">循环音乐名称</param>
        public void PlayBgm(string startName, string loopName = "")
        {

            var bgmPlayer = InitializePlayer(ref m_BgmPlayer, "BgmPlayer");
            if (bgmPlayer != null)
            {
                try
                {
                    bgmPlayer.SetVolume(m_fBgmVolume);
                    if (loopName == "")
                        loopName = startName;
                    bgmPlayer.Play(startName, loopName);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing BGM: {ex.Message}");
                }
            }
        }
        public void StopBgm()
        {
            m_BgmPlayer?.Stop();
        }

        public void PlayOneShot(AudioClip clip)
        {
            if (clip == null)
                return;
            var oneShotPlayer = InitializePlayer(ref m_OneShotPlayer, "OneShotPlayer");
            if (oneShotPlayer != null)
            {
                try
                {
                    oneShotPlayer.SetVolume(m_fEffectVolume);
                    oneShotPlayer.Play(clip);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing BGM: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 播放单通道
        /// </summary>
        /// <param name="startName"></param>
        public void PlayOneShot(string startName)
        {

            var oneShotPlayer = InitializePlayer(ref m_OneShotPlayer, "OneShotPlayer");
            if (oneShotPlayer != null)
            {
                try
                {
                    oneShotPlayer.SetVolume(m_fEffectVolume);
                    oneShotPlayer.Play(startName);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing BGM: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 播放技能音效
        /// </summary>
        /// <param name="audioName">音频名称</param>
        public void PlaySkillEffect(string audioName)
        {
            if (string.IsNullOrEmpty(audioName))
            {
                Debug.LogWarning("Invalid input: audioName is null or empty.");
                return;
            }

            var skillPlayer = InitializePlayer(ref m_SkillPlayer, "SkillPlayer");
            if (skillPlayer != null)
            {
                try
                {
                    skillPlayer.SetVolume(m_fEffectVolume);
                    skillPlayer.Play(audioName);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing Skill Effect: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 播放UI音效
        /// </summary>
        /// <param name="audioName">音频名称</param>
        public void PlayUIEffect(string audioName)
        {
            if (string.IsNullOrEmpty(audioName))
            {
                Debug.LogWarning("Invalid input: audioName is null or empty.");
                return;
            }

            var uiPlayer = InitializePlayer(ref m_UIPlayer, "UIPlayer");
            if (uiPlayer != null)
            {
                try
                {
                    uiPlayer.SetVolume(m_fEffectVolume);
                    uiPlayer.Play(audioName);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing UI Effect: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 播放场景音效
        /// </summary>
        /// <param name="audioName">音频名称</param>
        public void PlaySceneEffect(string audioName)
        {
            if (string.IsNullOrEmpty(audioName))
            {
                Debug.LogWarning("Invalid input: audioName is null or empty.");
                return;
            }

            var scenePlayer = InitializePlayer(ref m_ScenePlayer, "ScenePlayer");
            if (scenePlayer != null)
            {
                try
                {
                    scenePlayer.SetVolume(m_fEffectVolume);
                    scenePlayer.Play(audioName);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error playing UI Effect: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 添加音频源
        /// </summary>
        public static AudioSource AddAudioSource(GameObject go)
        {
            AudioSource audioSource = go.AddComponent<AudioSource>();
            audioSource.Stop();
            audioSource.playOnAwake = false;
            audioSource.rolloffMode = AudioRolloffMode.Linear;
            audioSource.loop = false;
            audioSource.minDistance = 0;
            audioSource.maxDistance = 20;
            audioSource.spatialBlend = 0.0f;

            return audioSource;
        }


    }
}